﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using TaskTodo.Todos;
using Volo.Abp.Data;
using Volo.Abp.Domain.Entities;
using Volo.Abp.EntityFrameworkCore;
using Yitter.IdGenerator;

namespace TaskTodo.EntityFrameworkCore
{
    [ConnectionStringName(TaskTodoDbProperties.ConnectionStringName)]
    public class TaskTodoDbContext : AbpDbContext<TaskTodoDbContext>, ITaskTodoDbContext
    {
        /* Add DbSet for each Aggregate Root here. Example:
         * public DbSet<Question> Questions { get; set; }
         */

        public TaskTodoDbContext(DbContextOptions<TaskTodoDbContext> options)
            : base(options)
        {

        }
        public DbSet<Todo> Todos { get; set; }
        public IIdGenerator _idGenerator { get; }

        public TaskTodoDbContext(DbContextOptions<TaskTodoDbContext> options, IIdGenerator idGenerator)
             : base(options)
        {
            _idGenerator = idGenerator;
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.ConfigureTaskTodo();
        }

        protected override void CheckAndSetId(EntityEntry entity)
        {
            IEntity<long> ety = entity.Entity as IEntity<long>;
            if (ety != null)
            {
                TrySetLongId(ety);
            }
            base.CheckAndSetId(entity);
        }

        protected virtual void TrySetLongId(IEntity<long> entity)
        {
            if (entity.Id != default)
            {
                return;
            }

            EntityHelper.TrySetId(
                entity,
                () => _idGenerator.NewLong(),
                true //DisableIdGenerationAttribute
            );
        }
    }
}